<?php
/**
 * 微信粉丝标签扩展.
 * User: Administrator
 * Date: 2019/12/9 0009
 * Time: 10:37
 */

namespace app\admin\traits\controller;


use service\DataService;
use service\LogService;
use service\WechatService;
use think\Db;

Trait WxTags{


    /**
     * 列表后置方法
     */
    protected function _index_data_filter(&$data){
        foreach ($data as &$vo) {
            $vo['type'] = $vo['id']< 100 ? "系统标签" : "自定义标签";
        }
    }


    /**
     * 添加表单前置方法
     * @param $data
     */
    protected function _add_form_filter(&$data){
        if($this->request->isPost()){
            empty($data['name']) && $this->error('粉丝标签名不能为空!');
            (Db::name($this->table)->where('name', $data['name'])->count() > 0) && $this->error('粉丝标签标签名已经存在, 请使用其它标签名!');
            $wechat = load_wechat('User');
            if (false === ($result = $wechat->createTags($data['name'])) && isset($result['tag'])) {
                $this->error("添加粉丝标签失败. {$wechat->errMsg}[{$wechat->errCode}]");
            }
            $result['tag']['count'] = 0;
            $data = $result['tag'];
        }
    }

    /**
     * 编辑表单前置方法
     * @param $data
     */
    protected function _edit_form_filter(&$data){
        if($this->request->isPost()){
            // 接收提交的数据
            list($name, $id) = [$this->request->post('name', ''), $this->request->post('id', '0')];
            $info = Db::name($this->table)->where('name', $name)->find();
            if (!empty($info)) {
                if (intval($info['id']) === intval($id)) {
                    $this->error('粉丝标签名没有改变, 无需修改!');
                }
                $this->error('标签已经存在, 使用其它名称再试!');
            }
            $wechat = load_wechat('User');
            $data = ['id' => $id, 'name' => $name];
            if (false !== $wechat->updateTag($id, $name) && false !== DataService::save($this->table, $data, 'id')) {
                $this->success('编辑标签成功!', '');
            }
            $this->error('编辑标签失败, 请稍后再试!' . $wechat->errMsg);
        }
    }

    /**
     * 删除粉丝标签
     */
    protected function _delete(&$data){
        $wechat = load_wechat('User');
        $status = DataService::update($this->table);
        if(false !== $status && false !== $wechat->delTag($data['id'])){
            return true;
        }
        return false;
    }

    /**
     * 同步粉丝标签
     */
    protected function _sync(){
        $table_name = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $this->table));
        Db::query("truncate table {$table_name}");
        //进行同步
        if(WechatService::syncFansTags()){
            LogService::write('微信管理','同步全部微信粉丝标签成功');
            return true;
        }
        return false;
    }
}